<template>
  <div class="user-container" v-loading="loading">
    <!-- 头部新增/搜索 -->
    <div class="user-haeder">
      <div class="user-add">
        <el-button type="primary" @click="dialogFormVisible = true"
          >新增用户</el-button
        >
      </div>
      <div class="user-search">
        <el-input
          v-model="searchInput"
          class="w-50 m-2"
          size="large"
          placeholder="请输入需要搜索的用户"
          :prefix-icon="Search"
        />
        <el-button size="large" @click="searchUser">搜索</el-button>
      </div>
    </div>
    <!-- 用户列表 -->
    <div class="user-tabel">
      <el-table :data="tableData" style="width: 100%" size="default">
        <el-table-column fixed prop="id" label="id" width="150" />
        <el-table-column prop="name" label="姓名" align="center" />
        <el-table-column prop="sex" label="性别" align="center" />
        <el-table-column prop="birthday" label="出生日期" align="center" />
        <el-table-column prop="address" label="住址" align="center" />
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button
              link
              type="danger"
              size="small"
              @click.prevent="deleteUser(scope.row)"
              >删除</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="updataRow(scope.row)"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <div class="user-page">
      <el-pagination
        background
        layout="->,prev, pager, next"
        :total="userTotal"
        v-model:page-size="limit"
        v-model:current-page="page"
        :hide-on-single-page="true"
        @current-change="handleChangePage"
      />
    </div>
  </div>
  <!-- 设置用户信息表单 -->
  <div class="updata-user">
    <el-drawer v-model="drawer" direction="rtl">
      <template #header>
        <h4>修改用户信息</h4>
      </template>
      <template #default>
        <div>
          <el-form
            label-width="100px"
            :model="formLabelAlign"
            style="max-width: 460px"
            v-model:disabled="isUpdata"
          >
            <el-form-item label="姓名">
              <el-input v-model="formLabelAlign.name" />
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="formLabelAlign.sex" placeholder="性别">
                <el-option label="男" value="A" />
                <el-option label="女" value="B" />
                <el-option label="其他" value="C" />
              </el-select>
            </el-form-item>
            <el-form-item label="出生日期">
              <el-date-picker
                v-model="formLabelAlign.birthday"
                type="date"
                placeholder="出生日期"
                size="large"
              />
            </el-form-item>
            <el-form-item label="住址">
              <el-input v-model="formLabelAlign.address" />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="setUserfrom">{{
            isUpdata ? "修改" : "确定"
          }}</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
  <!-- 添加用户表单 -->
  <div class="add-user">
    <el-dialog v-model="dialogFormVisible" title="新增用户">
      <el-form :model="form">
        <el-form-item label="用户姓名" :label-width="formLabelWidth">
          <el-input v-model.trim="form.name" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-select v-model.trim="form.sex" placeholder="性别">
            <el-option label="男" value="A" />
            <el-option label="女" value="B" />
            <el-option label="其他" value="C" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="出生日期"
            size="large"
          />
        </el-form-item>
        <el-form-item label="住址" :label-width="formLabelWidth">
          <el-input v-model="form.address" placeholder="xxx省 xxx市 xxx县" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser"> 添加 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import api from "../API";
import getDate from "../utils/getDate";
import { ElMessage } from "element-plus";

const loading = ref(false);
const drawer = ref(false);
const isUpdata = ref(true);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const searchInput = ref("");
const tableData = ref([]);
const userTotal = ref(0);
const page = ref(1);
const count = ref(0);
const limit = ref(15);
const formLabelAlign = ref({});

//初始化
onMounted(async () => {
  loading.value = true;
  userTotal.value = await getUserList(page.value, limit.value, count.value);
  loading.value = false;
});

//获取用户列表
const getUserList = async (page = 1, limit = 15, count = 0) => {
  const { list, total } = await api.getUserList({
    page,
    limit,
    count,
  });
  tableData.value = [...setSex(list)];
  return total;
};

//点击切换页码
const handleChangePage = async () => {
  loading.value = true;
  count.value = page.value * limit.value - limit.value;
  await getUserList(page.value, limit.value, count.value);
  loading.value = false;
};

//点击修改用户信息弹窗
const updataRow = (row) => {
  let user = { ...row };
  if (user.sex === "男") {
    user.sex = "A";
  } else if (user.sex === "女") {
    user.sex = "B";
  } else {
    user.sex = "C";
  }

  formLabelAlign.value = user;
  drawer.value = true;
};

//修改用户信息
const setUserfrom = async () => {
  if (isUpdata.value) {
    isUpdata.value = false;
  } else {
    if (
      formLabelAlign.value.name.length === 0 ||
      formLabelAlign.value.address.length === 0
    ) {
      ElMessage.warning("请填写用户名或地址信息");
      return;
    } else {
      loading.value = true;
      await api.setUser(formLabelAlign.value);
      tableData.value.forEach((item, i) => {
        if (item.id === formLabelAlign.value.id) {
          tableData.value[i] = setSex(formLabelAlign.value);
        }
      });
      drawer.value = false;
      loading.value = false;
    }
    isUpdata.value = true;
  }
};

//新增用户表单
const form = reactive({
  name: "",
  sex: "",
  birthday: "",
  address: "",
});
//新增用户
const addUser = async () => {
  loading.value = true;
  if (form.address && form.birthday && form.name && form.sex) {
    if (!+form.name && !+form.address) {
      const date = new Date(form.birthday).getTime();
      const addForm = {
        ...form,
        birthday: getDate(date, true),
      };
      userTotal.value = await api.addUser(addForm);
    } else {
      ElMessage.error("请填写正确的昵称与地址");
    }
  } else {
    ElMessage.error("请填写全部的内容");
  }
  loading.value = false;
};

//删除用户
const deleteUser = async (row) => {
  ElMessageBox.confirm("是否确认删除该用户？", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      await api.deleteUser(row.id);
      tableData.value.forEach((item) => {
        if (item.id === row.id) {
          const i = tableData.value.indexOf(item);
          tableData.value.splice(i, 1);
        }
      });
      loading.value = false;
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.warning("已取消");
    });
};

//搜索用户
const searchUser = async () => {
  loading.value = true;
  if (searchInput.value) {
    const res = await api.getSearchUser(searchInput.value);
    if (res) {
      tableData.value = [...setSex(res)];
    } else {
      ElMessage.warning("未查询到该用户");
    }
  } else {
    await getUserList(1, 15, 0);
  }
  searchInput.value = "";
  loading.value = false;
};

//设置性别
const setSex = (list) => {
  if (Array.isArray(list)) {
    return list.map((item) => {
      if (item.sex === "A") {
        item.sex = "男";
      } else if (item.sex === "B") {
        item.sex = "女";
      } else {
        item.sex = "其他";
      }
      return item;
    });
  } else {
    if (list.sex === "A") {
      list.sex = "男";
    } else if (list.sex === "B") {
      list.sex = "女";
    } else {
      list.sex = "其他";
    }
    return list;
  }
};
</script>

<style lang="less" scoped>
.user-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.user-haeder {
  flex-shrink: 0;
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
  & > div {
    margin: 0 20px;
  }
  .user-search {
    display: flex;
    .el-button {
      margin-left: 5px;
    }
  }
}
.user-tabel {
  flex: 1;
}
.user-page {
  flex-shrink: 0;
  margin: 20px 0;
  .el-pagination {
    margin: 0 20px;
  }
}
</style>
